package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.exception.CustomException;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.WmNewsDto;
import com.heima.model.wemedia.dtos.WmNewsPageReqDto;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmNewsMaterial;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.utils.thread.WmThreadLocalUtil;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.service.WmNewsAutoScanService;
import com.heima.wemedia.service.WmNewsService;
import com.heima.wemedia.service.WmNewsTaskService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class WmNewsServiceImpl extends ServiceImpl<WmNewsMapper, WmNews> implements WmNewsService {

    @Autowired
    private WmNewsMaterialMapper wmNewsMaterialMapper;

    @Autowired
    private WmMaterialMapper wmMaterialMapper;
    @Autowired
    private WmNewsMapper wmNewsMapper;
    @Autowired
    private WmNewsAutoScanService wmNewsAutoScanService;
    @Autowired
    private WmNewsTaskService wmNewsTaskService;

    /**
     * 查询文章
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult findAll(WmNewsPageReqDto dto) {
        WmUser wmUser = WmThreadLocalUtil.getUser();
        if(null == wmUser){
            throw new CustomException(AppHttpCodeEnum.NEED_LOGIN);
        }

        IPage page = new Page(dto.getPage(),dto.getSize());
        LambdaQueryWrapper<WmNews> queryWrapper = new LambdaQueryWrapper<>();

        //状态精确查询
        if(dto.getStatus() != null){
            queryWrapper.eq(WmNews::getStatus,dto.getStatus());
        }
        //频道精确查询
        if(dto.getChannelId() != null){
            queryWrapper.eq(WmNews::getChannelId,dto.getChannelId());
        }
        //关键字模糊查询
        if(dto.getKeyword() != null){
            queryWrapper.like(WmNews::getTitle,dto.getKeyword());
        }
        //时间范围查询
        if(dto.getBeginPubDate() != null && dto.getEndPubDate() != null){
            queryWrapper.between(WmNews::getPublishTime,dto.getBeginPubDate(),dto.getEndPubDate());
        }

        queryWrapper.eq(WmNews::getUserId,wmUser.getId());
        //发布时间倒序查询
        queryWrapper.orderByAsc(WmNews::getCreatedTime);

        page(page,queryWrapper);
        PageResponseResult responseResult = new PageResponseResult(dto.getPage(),dto.getSize(),(int)page.getTotal());
        responseResult.setData(page.getRecords());
        return responseResult;
    }

    /**
     * 发布文章或保存草稿
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult submitNews(WmNewsDto dto) throws Exception {
        if (dto == null || StringUtils.isEmpty(dto.getContent())) {
            throw new CustomException(AppHttpCodeEnum.PARAM_INVALID);
        }

        WmNews wmNews = new WmNews();
        BeanUtils.copyProperties(dto,wmNews);

        //补充其他数据
        wmNews.setUserId(WmThreadLocalUtil.getUser().getId());
        wmNews.setCreatedTime(new Date());
        wmNews.setEnable((short)1);
        wmNews.setSubmitedTime(new Date());

        // 判断是否为无图，是则更改数据，因为数据库设计，type字段部位负数，则会引起超越界限错误
        if(wmNews.getType() == -1){
            wmNews.setType(null);
        }

        if (dto.getImages() !=null && dto.getImages().size() > 0) {
            String images = StringUtils.join(dto.getImages(), ",");
            wmNews.setImages(images);
        }
        saveOrUpdateWmNews(wmNews);

        // 如果用户保存的是草稿则结束请求
        if (dto.getStatus().equals(WmNews.Status.NORMAL)) {
            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        }

        // 从内内容中抽取出所有的图片数据
        List<String> urls = ectractUrlInfo(dto.getContent());

        // 保存文章内容图片与素材的关系
        saveRelativeInfoForContent(wmNews,urls,(short)0);

        // 保存封面图片与素材之间的关系
        saveRelativeInfoForCover(wmNews,dto,(short)1,urls);

        // 发布文章成功进行审核阶段
        /*wmNewsAutoScanService.autoScanWmNews(wmNews.getId());*/
        wmNewsTaskService.addWmNewsToTask(wmNews);

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 根据ID查看文章
     * @param id
     * @return
     */
    @Override
    public ResponseResult seeNewsById(Integer id) {
        WmNews wmNews = wmNewsMapper.selectById(id);
        return ResponseResult.okResult(wmNews);
    }

    /**
     * 根据ID删除文章
     *
     * @param id 文章ID
     * @return 成功
     */
    @Override
    public ResponseResult deleteNewsById(Integer id) {
        WmNews wmNews = wmNewsMapper.selectById(id);
        if (wmNews == null) {
            return ResponseResult.errorResult(1002,"文章不存在");
        }
        if (wmNews.getStatus() == 9) {
            return ResponseResult.errorResult(501,"文章已发布，不能删除");
        }
        wmNewsMaterialMapper.delete(Wrappers.<WmNewsMaterial>lambdaQuery().eq(WmNewsMaterial::getNewsId,wmNews.getId()));
        wmNewsMapper.deleteById(id);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 保存封面图片与素材之间的关系
     * @param wmNews 文章
     * @param dto 页面传来的参数
     * @param type 1: 封面图片
     * @param urls 图片集合
     */
    private void saveRelativeInfoForCover(WmNews wmNews, WmNewsDto dto, short type,List<String> urls) {
        // 封面的图片 - 单图 多图 无图
        List<String> images = dto.getImages();
        // dto.getType()= -1 说明用户设置的封面为自动
        if (dto.getType() == -1) {
            if(urls.size() > 3 ){
                images = urls.stream().limit(3).collect(Collectors.toList());
                wmNews.setStatus((short)3);
            }else if(urls.size() >= 1){
                images = urls.stream().limit(1).collect(Collectors.toList());
                wmNews.setStatus((short)1);
            }else {
                wmNews.setStatus((short)0);
            }
        }

        // 跟新wmNews的数据
        updateById(wmNews);

        // 保存封面图片与素材之间的关系
        saveRelativeInfo(wmNews,images,type);
    }

    /**
     * 保存文章内容图片与素材的关系
     * @param urls 图片所有地址
     * @param wmNews 文章
     * @param type 0:内容图片
     */
    private void saveRelativeInfoForContent(WmNews wmNews,List<String> urls, short type) {
        saveRelativeInfo(wmNews, urls, type);
    }

    /**
     *  保存内容图片/封面图片与素材关系的公共方法
     * @param wmNews
     * @param urls
     * @param type
     */
    private void saveRelativeInfo(WmNews wmNews, List<String> urls, short type) {
        // 判断文章是否有图片，有则保存关系
        if(urls.size() > 0){
            // 对urls图片地址进行去重
            urls = urls.stream().distinct().collect(Collectors.toList());
            // 根据urls查询素材对象
            WmUser wmUser = WmThreadLocalUtil.getUser();
            if(null == wmUser){
                throw new CustomException(AppHttpCodeEnum.NEED_LOGIN);
            }
            List<WmMaterial> wmMaterials = wmMaterialMapper
                    .selectList(Wrappers.<WmMaterial>lambdaQuery()
                        .in(WmMaterial::getUrl, urls)
                        .eq(WmMaterial::getUserId, wmUser.getId()));

            // 判断素材是否在使用过程中呗删除
            if(wmMaterials == null || wmMaterials.size() != urls.size()){
                throw new CustomException(AppHttpCodeEnum.MATERIAL_REFERENCE_FAIL);
            }

            // 保存素材和文章之间的关系
            List<Integer> ids = wmMaterials.stream().map(item -> item.getId()).collect(Collectors.toList());
            wmNewsMaterialMapper.saveRelations(wmNews.getId(),ids, type);
        }
    }

    /**
     * 从内内容中抽取出所有的图片数据
     * @param content
     * @return
     */
    private List<String> ectractUrlInfo(String content) {
        List<Map> list = JSON.parseArray(content, Map.class);
        List<String> result = new ArrayList<>();

        for (Map map : list) {
            if("image".equals(map.get("type"))){
                result.add(map.get("value").toString());
            }
        }
        return result;
    }

    /**
     * 完成文章数据的保存或更新
     * @param wmNews
     */
    private void saveOrUpdateWmNews(WmNews wmNews) {
        if(null != wmNews.getId()){
            // 更新

            // 删除关联关系
            wmNewsMaterialMapper.delete(Wrappers.<WmNewsMaterial>lambdaQuery().eq(WmNewsMaterial::getNewsId,wmNews.getId()));

            // 更新文章数据到文章表
            updateById(wmNews);
        }else {
            save(wmNews);
        }

    }
}
